package com.example.micro.thread.counter;

import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 设计一个内存计数器
 * <p>
 * 用threadlocal保存每个线程long的副本，无锁自增，需要解决get求值问题，注意两点：
 * 1.线程异常退出会销毁线程创建新线程，需要try cache避免异常导致线程销毁
 * 2.如何拿到线程池所有线程来遍历threadlocal，通过线程池创建时的threadfactory保存创建的每个线程
 */
public class ThradeLocalCount1 {
    static class Counter {
        private static class Entry {
            long q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe;

            long count = 0;
        }

        private static final Lock lock = new ReentrantLock();
        private static final WeakHashMap<Thread, Entry> map = new WeakHashMap<>();

        private static final ThreadLocal<Entry> local = ThreadLocal.withInitial(Entry::new);

        public void increase() {
            Entry entry = local.get();
            long count = entry.count;
            if (count == 0) {
                lock.lock();
                try {
                    map.put(Thread.currentThread(), entry);
                } finally {
                    lock.unlock();
                }
            }
            entry.count = count + 1;
        }

        public long getAll() {
            return map.values().stream().map(entry -> entry.count).reduce(0L, Long::sum);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        int number = 100;
        Thread[] threads = new Thread[number];
        for (int i = 0; i < number; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100_000_000; j++) {
                    counter.increase();
                }
            });
        }
        for (Thread thread1 : threads) {
            thread1.start();
        }
        System.out.println(counter.getAll());
        for (Thread thread2 : threads) {
            thread2.join();
        }
        System.out.println(counter.getAll());
    }
}